/**
 * @description blog services
 * @author chengpeng
 */

const {
    Blog,
    User,
    UserRelation
} = require('../db/model/index')
const {
    formatUser,
    formatBlog
} = require('./_format')

/**
 * @description 创建微博
 * @author chengpeng
 * @param {Object} param0 创建微博参数 { userId, content, image }
 */
async function createBlog({
    userId,
    content,
    image
}) {
    const result = await Blog.create({
        userId,
        content,
        image
    })
    return result.dataValues
}

/**
 * @description 根据用户查询微博列表
 * @author chengpeng˝
 * @param {object} param0 查询参数 { userName, pageIndex = 0, pageSize = 10}
 */
async function getBlogListByUser({
    userName,
    pageIndex = 0,
    pageSize = 10
}) {
    const userWhereOpts = {}
    if (userName) {
        userWhereOpts.userName = userName
    }

    // 执行查询
    const result = await Blog.findAndCountAll({
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: [
            ['id', 'desc']
        ],
        include: [{
            model: User,
            attributes: ['userName', 'nickName', 'picture'],
            where: userWhereOpts
        }]
    })
    // result.count 总数
    // result.row 查询结果 数组

    let blogList = result.rows.map(row => row.dataValues)
    blogList = formatBlog(blogList)

    blogList = blogList.map(blogItem => {
        const user = blogItem.user.dataValues
        blogItem.user = formatUser(user)
        return blogItem
    })

    return {
        count: result.count,
        blogList
    }
}

/**
 * @description 获取关注者微博首页
 * @author chengpeng
 * @param {*} userId 
 * @param {*} pageIndex 
 * @param {*} pageSize 
 */
async function getFollowersBlogList({
    userId,
    pageIndex = 0,
    pageSize = 10
}) {
    const result = await Blog.findAndCountAll({
        limit: pageSize, // 每页多少条
        offset: pageSize * pageIndex, // 跳过多少条
        order: [
            ['id', 'desc']
        ],
        include: [{
                model: User,
                attributes: ['userName', 'nickName', 'picture']
            },
            {
                model: UserRelation,
                attributes: ['userId', 'followerId'],
                where: {
                    userId
                }
            }
        ]
    })

    let blogList = result.rows.map(item => item.dataValues)
    blogList = formatBlog(blogList)
    blogList = blogList.map(item => {
        item.user = formatUser(item.user.dataValues)
        return item
    })
    return {
        count: result.count,
        blogList
    }
}

module.exports = {
    createBlog,
    getBlogListByUser,
    getFollowersBlogList
}